package husc.se.ndung.soiphubaimobile;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import org.ksoap2.serialization.SoapPrimitive;

import java.util.ArrayList;

import husc.se.ndung.soiphubaimobile.Entity.ChiTietMay;
import husc.se.ndung.soiphubaimobile.Entity.CongDoan;
import husc.se.ndung.soiphubaimobile.Entity.MaySanXuat;


public class MainActivity extends ActionBarActivity implements FragmentChiTietMay.OnFragmentInteractionListener,
        FragmentCongDoan.OnFragmentInteractionCongDoanListener, FragmentMaySanXuat.OnFragmentInteractionMaySanXuatListener {
    private ProgressDialog m_ProgressDialog;
    private Button mBtnBack;
    private CongDoan mCongDoan;
    private MaySanXuat mMay;
    private Integer mCurrentFragment;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            asynLogin();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnBack = (Button) findViewById(R.id.refesh);
        m_ProgressDialog = new ProgressDialog(this);
        m_ProgressDialog.setTitle(getString(R.string.processLogin));
        m_ProgressDialog.setMessage(getResources().getText(R.string.waitingLabel));
        m_ProgressDialog.setMax(20);
        m_ProgressDialog.setProgress(0);
        asynLogin();
    }

    @Override
    public void onBackPressed() {
        //
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.title_exit);
        builder.setMessage(R.string.message_exit);
        builder.setNegativeButton(R.string.cancelbutton, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton(R.string.okbutton, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.show();
    }

    void asynLogin() {
        final AsyncTask<Void, Integer, Void> asyncTaskLoad = new AsyncTask<Void, Integer, Void>() {
            String msg;

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    msg = logIn();
                } catch (Exception e) {
                    Log.d("Loi", e.toString());
                    msg = "error";
                } finally {
                    return null;
                }
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                m_ProgressDialog.show();
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                m_ProgressDialog.dismiss();
                if (msg != null) {
                    if (msg.compareTo("error") == 0) {
                        finish();
                        Intent intent = new Intent(MainActivity.this, Login.class);
                        startActivity(intent);
                    } else {
                        if (msg.compareTo("true") == 0) {
                            mCurrentFragment = 0;
                            Fragment fragment = FragmentCongDoan.newInstance();
                            FragmentManager fragmentManager = getFragmentManager();
                            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
                            MainActivity.this.setTitle(R.string.title_congdoan);

                        } else {
                            finish();
                            Intent intent = new Intent(MainActivity.this, Login.class);
                            startActivity(intent);
                        }
                    }
                }
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                Log.d("Asyntask values: ", values.toString());
            }
        }.execute();
    }

    private String logIn() throws Exception {
        ArrayList<String> params = new ArrayList<String>();
        params.add("userName:" + Utils.getValueByKey(this, Utils.KeyUserName, ""));
        params.add("passWord:" + Utils.getValueByKey(this, Utils.KeyPassword, ""));
        SoapPrimitive response = (SoapPrimitive) Utils.sendRequest(this, "LogIn", params);
        return response.toString();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            //Intent intent = new Intent(MainActivity.this, SettingActivity.class);
            //startActivity(intent);
            //startActivityForResult(intent, 1);

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void logOut(View v) {
        Utils.setKeyValue(this, "UserName", "");
        Utils.setKeyValue(this, "Password", "");
        finish();
        Intent intent = new Intent(this, Login.class);
        startActivity(intent);
    }

    public void refresh(View v) {
        if (mCurrentFragment == 2) {
            onFragmentInteractionCongDoan(mCongDoan);
        } else if (mCurrentFragment == 1 || mCurrentFragment == 0) {
            Fragment fragment = FragmentCongDoan.newInstance();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
            MainActivity.this.setTitle(R.string.title_congdoan);
            mBtnBack.setText(R.string.lb_btnRefresh);
        }
    }

    public void info(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(getString(R.string.information));
        builder.setMessage(getString(R.string.copyright) + "\r\n" + getString(R.string.author) + "\r\n" + getString(R.string.email) + "\r\n" + getString(R.string.phone));
        builder.setNegativeButton(getString(R.string.okbutton), null);
        builder.show();
    }

    @Override
    public void onFragmentInteraction(ChiTietMay ctm) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.alertTitle);
        builder.setMessage(
                getString(R.string.tenchitietmay) + ctm.GetTenChiTietMay() + "\r\n" +
                        getString(R.string.tennhiemvubaotri) + ctm.GetTenNhiemVuBaoTri() + "\r\n" +
                        getString(R.string.hanbaotri) + ctm.GetHanBaoTri() + getString(R.string.lbngay)
        );
        builder.create().show();
    }

    @Override
    public void onFragmentInteractionCongDoan(CongDoan cd) {
        mBtnBack.setText(R.string.label_btnBack);
        mCongDoan = cd;
        mCurrentFragment = 1;
        MainActivity.this.setTitle(R.string.title_maysanxuat);
        Fragment fragment = FragmentMaySanXuat.newInstance(cd.getMaCongDoan());
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
    }

    @Override
    public void onFragmentInteractionMaySanXuat(MaySanXuat may) {
        mBtnBack.setText(R.string.label_btnBack);
        mMay = may;
        mCurrentFragment = 2;
        MainActivity.this.setTitle(R.string.title_chitietmay);
        Fragment fragment = FragmentChiTietMay.newInstance(may.getMaMaySanXuat());
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
    }
}
